package com.Fen.service.impl;

import com.Fen.dto.GoodsSalesDTO;
import com.Fen.entity.Orders;
import com.Fen.mapper.OrderMapper;
import com.Fen.mapper.UserMapper;
import com.Fen.service.ReportService;
import com.Fen.service.WorkspaceService;
import com.Fen.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 营业额统计
     * @param beginTime
     * @param endTime
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate beginTime, LocalDate endTime) {

        //获取日期列表
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(beginTime);

        while (!beginTime.equals(endTime)){
            beginTime=beginTime.plusDays(1);
            dateList.add(beginTime);
        }

        String dates = StringUtils.join(dateList, ",");


        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //获取日期的营业额
            LocalDateTime begin= LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end=LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",begin);
            map.put("end",end);
            map.put("status", Orders.COMPLETED);
            Double  turnover=orderMapper.sumByMap(map);
            turnover=turnover==null ? 0.0 :turnover;
            turnoverList.add(turnover);
        }

        String money = StringUtils.join(turnoverList, ",");

        TurnoverReportVO turnoverReportVO=TurnoverReportVO.builder()
                .dateList(dates)
                .turnoverList(money)
                .build();


        return turnoverReportVO;
    }

    @Override
    public UserReportVO getuserStatistics(LocalDate beginTime, LocalDate endTime) {
        //获取日期列表
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(beginTime);

        while (!beginTime.equals(endTime)){
            beginTime=beginTime.plusDays(1);
            dateList.add(beginTime);
        }

        String dates = StringUtils.join(dateList, ",");

        //统计用户总量
        List<Integer> userList=new ArrayList<>();
        List<Integer> addUserList=new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime begin= LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end=LocalDateTime.of(localDate, LocalTime.MAX);

            Map map=new HashMap<>();
            map.put("begin",begin);
            Integer totalUserCount=userMapper.statisticsUser(map);
            map.put("end",end);
            Integer adduserCount=userMapper.statisticsUser(map);

            userList.add(totalUserCount);
            addUserList.add(adduserCount);

        }

        String total = StringUtils.join(userList, ",");
        String add = StringUtils.join(addUserList, ",");

        return UserReportVO.builder()
                .dateList(dates)
                .totalUserList(total)
                .newUserList(add)
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getorderStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();

        for (LocalDate localDate : dateList) {
            //查询每天订单数量
            LocalDateTime beginTime= LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);

            Integer everyDayTotal=orderMapper.countByMap(map);
            orderCountList.add(everyDayTotal);

            //查询每天有效订单数量
            map.put("status", Orders.COMPLETED);
            Integer everyDayValid=orderMapper.countByMap(map);
            validOrderCountList.add(everyDayValid);
        }

        String dates = StringUtils.join(dateList, ",");
        String orderCountStr = StringUtils.join(orderCountList, ",");
        String validOrderCountStr = StringUtils.join(validOrderCountList, ",");


        Integer totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount=validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate= 0.0;
        if(totalOrderCount!=0) {
            orderCompletionRate= validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(dates)
                .orderCountList(orderCountStr)
                .validOrderCountList(validOrderCountStr)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO topTen(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> names = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String namesStr = StringUtils.join(names, ",");

        List<Integer> numbers = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numbersStr = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder()
                .nameList(namesStr)
                .numberList(numbersStr)
                .build();
    }

    /**
     * 导出报表
     * @param response
     */
    public void export(HttpServletResponse response){

        //查询数据
        LocalDate begin = LocalDate.now().minusMonths(1);
        LocalDate end = LocalDate.now().minusDays(1);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        BusinessDataVO businessDataVO= workspaceService.getBusinessData(beginTime, endTime);

        //通过POI将数据写入Excel文件中
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excal文件
            XSSFWorkbook excel=new XSSFWorkbook(in);

            //获取第一个sheet
            XSSFSheet sheet=excel.getSheetAt(0);

            //设置时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+" 至 "+end);

            //设置数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据30天
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                LocalDateTime dateBegin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime dateEnd = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(dateBegin, dateEnd);
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());
            }


            //通过输出流将Excal文件下载但客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);


            //关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
